package com.cn.web.global.service;

import com.alibaba.fastjson.JSON;
import com.cn.global.GlobalParamtersUtil;
import com.cn.global.GlobalparamtersExt;
import com.cn.web.global.mapper.IGlobalParamtersMapper;
import com.cn.web.global.vo.GlobalParamtersDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

/**
 * description: GlobalParamtersService <br>
 * date: 23.10.17 16:41 <br>
 * author: cn_yaojin <br>
 * version: 1.0 <br>
 */
@Service
@Slf4j
public class GlobalParamtersService implements ApplicationRunner {

    @Autowired
    private IGlobalParamtersMapper globalParamtersMapper;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            start();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("初始化全局参数异常");
        }
    }

    /**
     * 防止缓存丢失导致的全局参数加载失败
     */
    public void start() {
        var data = GlobalParamtersUtil.get();
        if (data == null) {
            var sourceData = this.get();
            if (sourceData != null && StringUtils.isNotEmpty(sourceData.getContent())) {
                GlobalparamtersExt ext = JSON.parseObject(sourceData.getContent(), GlobalparamtersExt.class);
                GlobalParamtersUtil.add(ext);
            }
        }
    }

    public void add(String txt) {
        var data = this.get();
        if (data == null) {
            data = new GlobalParamtersDTO();
            data.setId(1L);
            data.setContent(txt);
            this.globalParamtersMapper.insert(data);
        } else {
            data.setContent(txt);
            this.globalParamtersMapper.updateById(data);
        }
    }

    public GlobalParamtersDTO get() {
        return this.globalParamtersMapper.selectById(1);
    }

    public GlobalparamtersExt find() {
        var sourceData = this.get();
        if (sourceData != null && StringUtils.isNotEmpty(sourceData.getContent())) {
            GlobalparamtersExt ext = JSON.parseObject(sourceData.getContent(), GlobalparamtersExt.class);
            return ext;
        }
        return null;
    }

}
